package com.zz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.RowRenderData;
import com.zz.common.ESignParameter;
import com.zz.common.ZohoRecord;
import com.zz.service.SaleService;
import com.zz.utils.*;
import com.zz.word.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Slf4j
@Service
public class SaleServiceImpl implements SaleService {

    @Autowired
    ZohoRecord zohoRecord;

    @Autowired
    ESignParameter parameter;

    @Autowired
    IncentiveServiceImpl incentiveService;

    @Override
    public ResultUtil getTemplate(JSONObject data) {
        String operationId = data.getString("operationId");
        if (StringUtils.isNotBlank(operationId)) {
            System.out.println("销售指标 parameter = " + data.toJSONString());
            // 1 校验条件，当前操作人
            boolean isCheck = checkLoginUser(operationId);
            if (isCheck) {
                // word模板路径
                //String templatePath = FileUtil.getResourceWordTemplate();
                String templatePath = FileUtil.getRelativeResourceFilePathWord();

                //String resource = templatePath + "sale_template.docx";
                String resource = templatePath + "sale_template.doc";

                // 传入word的数据
                SaleData wordData = new SaleData();

                wordData.setProvince(data.getString("province"));
                wordData.setProduct(data.getString("product"));
                wordData.setSize(data.getString("size"));
                wordData.setEnterprise(data.getString("enterprise"));
                wordData.setYear(DateUtil.getYearByDate(new Date()));
                wordData.setMonth(DateUtil.getMonthByDate(new Date()));
                wordData.setDay(DateUtil.getDayByDate(new Date()));

                // word
                SaleTableData detailTable = new SaleTableData();
                // 销售指标
                List<RowRenderData> wordSaleList = new ArrayList<>();
                List<JSONObject> saleList = data.getJSONArray("list").toJavaList(JSONObject.class);
                for (JSONObject sale : saleList) {
                    String name = sale.getString("name");
                    List<JSONObject> detailList = sale.getJSONArray("detail").toJavaList(JSONObject.class);
                    for (JSONObject detail : detailList) {
                        RowRenderData saleRowData = WordUtil.getSaleRowData(name, detail);
                        wordSaleList.add(saleRowData);
                    }
                }
                detailTable.setSales(wordSaleList);

                // 合计
                RowRenderData sumRowData = WordUtil.getSumRowData(saleList);
                List<RowRenderData> wordSumList = new ArrayList<>();
                wordSumList.add(sumRowData);
                detailTable.setSums(wordSumList);

                wordData.setDetailTable(detailTable);

                Configure config = Configure.builder().bind("detail_table", new SalePolicy()).build();
                XWPFTemplate template = XWPFTemplate.compile(resource, config).render(wordData);
                //String fileFullPath = templatePath + "目标医院销售指标模板.docx";

                List<JSONObject> basicFileList = BiologicalApiUtil.getBasicFile(zohoRecord.getAccessToken(), data.getString("id"));
                String accountName = "";
                if (basicFileList.size() > 0) {
                    JSONObject basicData = basicFileList.get(0);
                    accountName = basicData.getString("Account_Name");
                }

                String fileFullPath = templatePath + accountName + "_目标医院销售指标.doc";
                try {
                    template.writeToFile(fileFullPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }


                // 文件流方式
                String id = data.getString("id");
                //String url = "https://www.zohoapis.com.cn/crm/v3/TargetHospitalIndicatorList/" + id + "/Attachments";
                String url = "https://www.zohoapis.com.cn/crm/v3/Accounts/" + id + "/Attachments"; // 在基础档案的附件下

                JSONObject jsonObject = HttpUtil.postFileByFileStream(zohoRecord.getAccessToken(), fileFullPath, url);
                if (jsonObject.toJSONString().contains("SUCCESS")) {
                    log.info("模板传送成功，目标医院销售指标id = " + id);
                    return ResultUtil.success("目标医院销售指标模板下载成功");
                } else {
                    log.info("模板传送失败" + jsonObject.toJSONString());
                    return ResultUtil.error("目标医院销售指标模板下载失败,请联系管理员");
                }
            }
        }
        return ResultUtil.error("当前操作人没有操作权限");
    }

    @Override
    public ResultUtil getChangeTemplate(JSONObject data) {
        String operationId = data.getString("operationId");
        if (StringUtils.isNotBlank(operationId)) {
            System.out.println("销售指标变更 parameter = " + data.toJSONString());
            // 1 校验条件，当前操作人
            boolean isCheck = checkLoginUser(operationId);

            if (isCheck) {
                // word模板路径
                //String templatePath = FileUtil.getResourceWordTemplate();
                String templatePath = FileUtil.getRelativeResourceFilePathWord();
                //String resource = templatePath + "change_template.docx";
                String resource = templatePath + "change_template.doc";

                // 传入word的数据
                SaleChangeData wordData = new SaleChangeData();

                wordData.setProvince(data.getString("province"));
                wordData.setHosName(data.getString("hosName"));
                wordData.setProduct(data.getString("product"));
                wordData.setSize(data.getString("size"));
                wordData.setEnterprise(data.getString("enterprise"));
                wordData.setYear(DateUtil.getYearByDate(new Date()));
                wordData.setMonth(DateUtil.getMonthByDate(new Date()));
                wordData.setDay(DateUtil.getDayByDate(new Date()));

                // word
                SaleChangeTableData detailTable = new SaleChangeTableData();

                detailTable.setSalesData(data);

                wordData.setDetailTable(detailTable);

                Configure config = Configure.builder().bind("detail_table", new SaleChangePolicy()).build();
                XWPFTemplate template = XWPFTemplate.compile(resource, config).render(wordData);
                //String fileFullPath = templatePath + "目标医院销售指标变更明细.docx";


                // 目标医院的基础档案名称
                String name = "";
                List<JSONObject> targetHospitalList = BiologicalApiUtil.getTargetHospital(zohoRecord.getAccessToken(), data.getString("id"));
                if (targetHospitalList.size() > 0) {
                    JSONObject targetHospital = targetHospitalList.get(0);
                    name = targetHospital.getString("Name");
                }

                String fileFullPath = templatePath + name + "_目标医院销售指标变更明细.doc";
                try {
                    template.writeToFile(fileFullPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 文件流方式
                String id = data.getString("id");
                //String url = "https://www.zohoapis.com.cn/crm/v3/TargetHospitalSaleTargetChangeList/" + id + "/Attachments";
                String url = "https://www.zohoapis.com.cn/crm/v3/TargetHospital/" + id + "/Attachments"; // 在目标医院的附件下

                JSONObject jsonObject = HttpUtil.postFileByFileStream(zohoRecord.getAccessToken(), fileFullPath, url);
                if (jsonObject.toJSONString().contains("SUCCESS")) {
                    log.info("模板传送成功，目标医院销售指标变更明细id = " + id);
                    return ResultUtil.success("目标医院销售指标变更明细模板下载成功");
                } else {
                    log.info("模板传送失败" + jsonObject.toJSONString());
                    return ResultUtil.error("目标医院销售指标变更明细模板下载失败,请联系管理员");
                }
            }
        }

        return ResultUtil.error("当前操作人没有操作权限");
    }

    public boolean checkLoginUser(String operationId) {
        boolean isCheck = false;
        List<JSONObject> userData = CrmApiUtil.getUserDataById(zohoRecord.getAccessToken(), operationId);
        if (!CollectionUtils.isEmpty(userData)) {
            JSONObject user = userData.get(0);
            JSONObject profile = user.getJSONObject("profile");
            if (Objects.nonNull(profile)) {
                String roleName = profile.getString("name");
                log.info("当前用户角色名称：" + roleName);
                if (roleName.equalsIgnoreCase("省区经理") ||
                        roleName.equalsIgnoreCase("地区经理") ||
                        roleName.equalsIgnoreCase("商务经理") ||
                        roleName.equalsIgnoreCase("商务大区经理") ||
                        roleName.equalsIgnoreCase("系统管理员") ||
                        roleName.equalsIgnoreCase("Administrator")) {
                    isCheck = true;
                }
            }
        }
        return isCheck;
    }
}
